const response = require("../utils/response");
const router = require("koa-router")();
const mongoose = require("mongoose");
const {
    buildRangeQuery,
    paginate,
} = require("../utils/dberrordeal");
const { Stock, hydata } = require("../models/socks")
// 去重并生成新的集合
router.get('/industries', async (ctx, next) => {
    try {
        // 使用聚合管道去重
        const pipeline = [
            {
                $group: {
                    _id: "$所处行业",
                    count: { $sum: 1 }
                }
            },
            {
                $project: {
                    _id: 0,
                    所处行业: "$_id",
                    count: 1
                }
            }
        ];

        const uniqueIndustries = await Stock.aggregate(pipeline);

        // 插入到新的集合中
        const Industry = mongoose.model('Industry', new mongoose.Schema({}, { strict: false }), 'industries');

        await Industry.deleteMany({}); // 清空目标集合
        await Industry.insertMany(uniqueIndustries);

        response.success(ctx, { data: uniqueIndustries });
    }
    catch (error) {
        console.log(error);
        response.error(ctx, {});
    }
});


router.post("/getsockList", async (ctx, next) => {
    let data = ctx.request.body;
    let params = ctx.request.query;
    // 动态构建查询条件
    let query = {};
    query['最新公告日期'] = data?.ggrq
        ? buildRangeQuery(data.ggrq
        [0], data.ggrq
        [1], "time")
        : undefined;

    if (data?.name) {
        const regex = new RegExp(data.name, 'i'); // 'i' 表示忽略大小写
        query.$or = [
            { '股票简称': regex },
            { '股票代码': regex }
        ];
    }
    query['每股收益'] = buildRangeQuery(+data?.minmgsy, +data?.maxmgsy);
    query['营业收入-营业收入'] = buildRangeQuery(+data?.minyysr, +data?.maxyysr);
    query['营业收入-同比增长'] = buildRangeQuery(+data?.minystbzz, +data?.maxystbzz);
    query['营业收入-季度环比增长'] = buildRangeQuery(+data?.minysjdhbzz, +data?.maxysjdhbzz);
    query['净利润-净利润'] = buildRangeQuery(+data?.minjlr, +data?.maxjlr);
    query['净利润-同比增长'] = buildRangeQuery(+data?.minjltbzz, +data?.maxjltbzz);
    query['净利润-季度环比增长'] = buildRangeQuery(+data?.minjljdzz, +data?.maxjljdzz);
    query['每股净资产'] = buildRangeQuery(+data?.minmgjzc, +data?.maxmgjzc);
    query['净资产收益率'] = buildRangeQuery(+data?.minjzcsy, +data?.maxjzcsy);
    query['每股经营现金流量'] = buildRangeQuery(+data?.minmgjyxjl, +data?.maxmgjyxjl);
    query['销售毛利率'] = buildRangeQuery(+data?.minxsmlv, +data?.maxsmlv);
    if (data?.hy) {
        let ff = await hydata.findOne({ _id: data?.hy })
        query['所处行业'] = ff['所处行业']
    }
    // 移除未定义的查询条件
    Object.keys(query).forEach(
        (key) => query[key] === undefined && delete query[key]
    );

    let fres = await paginate(Stock, query, params, []);
    response.success(ctx, {
        data: {
            list: fres.results,
            total: fres.total,
        },
    });
});



router.get("/getindustriesList", async (ctx, next) => {
    try {
        // 使用聚合管道去重
        const pipeline = [
            {
                $group: {
                    _id: "$所处行业",
                    count: { $sum: 1 }
                }
            },
            {
                $project: {
                    _id: 0,
                    所处行业: "$_id",
                    count: 1
                }
            }
        ];

        const uniqueIndustries = await Stock.aggregate(pipeline);

        // 插入到新的集合中
        const Industry = mongoose.model('Industry', new mongoose.Schema({}, { strict: false }), 'industries');

        await Industry.deleteMany({}); // 清空目标集合
        await Industry.insertMany(uniqueIndustries);

        response.success(ctx, { data: uniqueIndustries });
    }
    catch (error) {
        console.log(error);
        response.error(ctx, {});
    }
    await hydata.find()
        .then((res) => {
            response.success(ctx, { data: res });
        })

});
module.exports = router;
